const db = require('../db/index')

let get_ps_ids = (req, res) => {
    let sql = "select ps_ids from sp_manager,sp_role where sp_manager.role_id=sp_role.role_id and mg_name=?"
    return new Promise((resolve, reject) => {
        db.query(sql, req.user.mg_name, (err, result) => {
            if (err) return res.sendErr(err)
            let ps_ids_arr = result[0].ps_ids === '' ? [] : result[0].ps_ids.split(",")
            resolve(ps_ids_arr)
        })
    })
}
let getLevel1 = (ps_ids_arr) => {
    let sql = "select * from sp_permission where ps_level ='1' and ps_id = ?"
    return new Promise((resolve, reject) => {
        let level1_arr = []
        ps_ids_arr.forEach((item, index) => {
            db.query(sql, item, (err, result) => {
                if (err) return res.sendErr(err)
                result.length !== 0 && level1_arr.push(result[0])
                if (index === ps_ids_arr.length - 1) {
                    resolve(level1_arr)
                }
            })
        });
    })
}
let getLevel0 = (ps_ids_arr) => {
    let sql = "select * from sp_permission where ps_level ='0' and ps_id = ?"
    return new Promise((resolve, reject) => {
        let level0_arr = []
        ps_ids_arr.forEach((item, index) => {
            db.query(sql, item, (err, result) => {
                if (err) return res.sendErr(err)
                result.length !== 0 && level0_arr.push(result[0])
                if (index === ps_ids_arr.length - 1) {
                    resolve(level0_arr)
                }
            })
        });
    })
}
let getLevel0_1 = (level0_arr, level1_arr) => {
    return new Promise((resolve, reject) => {
        level0_arr.forEach((item1, index1) => {
            item1.children = []
            level1_arr.forEach((item2, index2) => {
                if (item2.ps_pid === item1.ps_id) {
                    item1.children.push(item2)
                }
            })
            if (index1 === level0_arr.length - 1) {
                resolve(level0_arr)
            }
        })
    })
}
const getSlideItems = async (req, res) => {
    let ps_ids_arr = await get_ps_ids(req, res)
    if (ps_ids_arr.length === 0) {
        return res.send({
            status: 200,
            message: "无任何权限",
            data: []
        })
    }
    let level1_arr = await getLevel1(ps_ids_arr)
    let level0_arr = await getLevel0(ps_ids_arr)
    let level0_1_arr = await getLevel0_1(level0_arr, level1_arr)
    res.send({
        status: 200,
        message: "获取列表成功",
        data: level0_1_arr
    })
}

module.exports = {
    getSlideItems
}